/**
 * 
 * If you have edited the file, please update
 * all the last-modified fields manually. Thanks!
 *
 * @last-modified by: 
 * @last-modified date: 
 * @last-modified time: 
 *
 * @author Swee Zhi
 * @date-created Sep 20, 2011    @time-created 1:56:37 PM
 *
 * @project: 
 * @module: 
 * @institution: 
 *
 */



/** 
 * note for usage of this validation class
 * paste this in faces-config.xml after <application> </application> tag
 * 
 *  <validator>
        <validator-id>checkValidEmail</validator-id>
        <validator-class>util.validation.PasswordMatchValidator</validator-class>
    </validator>
 */
package util.validator;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import util.localization.WebLocalization;


@ManagedBean
@RequestScoped
public class PasswordMatchValidator implements Validator {
    private WebLocalization localization;
    private String preferredLocale;
    
    public PasswordMatchValidator() {
        /* LOCALIZATION */
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        /* END LOCALIZATION */
    }

    @Override
    public void validate(FacesContext facesContext, UIComponent component, Object value) throws ValidatorException {
        // Obtain the first password component from f:attribute.
        UIInput passwordComponent = (UIInput) component.getAttributes().get("pw");

        // Get its value, the entered password of the first field.
        String password = (String) passwordComponent.getValue();

        // Cast the value of the entered password of the second field back to String.
        String confirm = (String) value;

        // Compare the first password with the second password.
        if (!password.equals(confirm)) {
            FacesMessage message = new FacesMessage();
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            
            String errorMessage = "";
            if(preferredLocale.equals("en_US")) errorMessage = "Passwords do not match.";
            else if(preferredLocale.equals("en_SG")) errorMessage = "Passwords do not match.";
            else if(preferredLocale.equals("zh_CN")) errorMessage = "密码不相符。";
            else if(preferredLocale.equals("ms_MY")) errorMessage = "Kata laluan tidak sepadan.";
        
            message.setSummary(errorMessage);
            throw new ValidatorException(message);
        }
    }
    
}
